import random

from django.http import HttpResponse,JsonResponse
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from meiduo_mall.settings.dev import logger


class SMSCodeView(View):
    def get(self,request,mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        try:
            img_redis_client = get_redis_connection('verify_image_code')
            redis_img_code = img_redis_client.get('img_%s'% uuid)

            if not redis_img_code:
                return JsonResponse({'code':"4001",'errmsg':'图形验证码失效了！'})
            if redis_img_code.decode().lower() != image_code.lower():
                return JsonResponse({'code':"4001",'errmsg':'图形验证码错误！'})

            img_redis_client.delete('img_%s'% uuid)

        except Exception as e:
            logger.error(e)

        sms_redis_client = get_redis_connection('sms_code')
        send_flag = sms_redis_client.get('send_flag_%s' %mobile)
        if send_flag:
            return JsonResponse({'code': '4002', 'errmsg': '发送短信频繁'})

        sms_code = '%06d' % random.randint(0,999999)

        try:
            p1 =sms_redis_client.pipline()
            p1.setex('send_flag_%s' %send_flag,"a",60)
            p1.setex('sms_%s' %mobile,sms_code)
            p1.execute()
        except Exception as e:
            logger.error(e)

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)
        return JsonResponse({'code': '0', 'errmsg': '发送短信成功'})

class ImageCodeView(View):
    def get(self,request,uuid):
        text, image_code = captcha.generate_captcha()

        from django_redis import get_redis_connection
        image_redis_clent = get_redis_connection('verify_image_code')
        image_redis_clent.setex("img_%s"%uuid,300,text)

        return HttpResponse(image_code,content_type='image/jpeg')
